//
//  StorageCategoryViewController.m
//  danpin
//
//  Created by chuangjia on 15/12/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "StorageCategoryViewController.h"
#import "CHTCollectionViewWaterfallLayout.h"
#import "RacksCollectionViewCell.h"
#import "RacksCollectionHeaderView.h"
#import "RacksCollectionFooterView.h"
#import "SVPullToRefreshView+OY_PullRefreshView.h"
#import "WebViewController.h"
#import "NiubiSearchVC.h"
#import "StorageBrandViewController.h"
#import "StorageInfo.h"
//===============
#import "LMComBoxView.h"
#define kDropDownListTag 10000
#define COMBOXHEIGHT 35
#import "JianbianView.h"
@interface StorageCategoryViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,CHTCollectionViewDelegateWaterfallLayout,LMComBoxViewDelegate>
{
    
}
@property(nonatomic,strong)UICollectionView *myCollectionView;
//
@property(nonatomic,strong)NSMutableArray *categoryDatas;
@property(nonatomic,strong)NSMutableArray *twocategoryDatas;
@property(nonatomic,strong)NSMutableArray *threecategoryDatas;
@property(nonatomic,strong)NSMutableArray *sortDatas;
@property(nonatomic,strong)NSMutableArray *brandDatas;
@property(nonatomic,strong)NSMutableArray *itemDatas;
@property(nonatomic,strong)NSString *currentPage;
@property(nonatomic,assign)BOOL isLoadFinished;
@property(nonatomic,assign)BOOL isRequesting;


@property(nonatomic,assign)BOOL isSetUpBgScrollView;
@property(nonatomic,strong)NSString* endmessage;
@property(nonatomic,strong)NSString* timestamp;
//
@property(nonatomic,strong)UIView* comboxview;
@property(nonatomic,assign)BOOL comboxOpen;
@property(nonatomic,assign)CGFloat lastOffsetY;
@end

@implementation StorageCategoryViewController
@synthesize navtitle=_navtitle;
@synthesize myCollectionView=_myCollectionView;
@synthesize itemDatas=_itemDatas;
@synthesize currentPage=_currentPage;
@synthesize categoryDatas=_categoryDatas;
@synthesize twocategoryDatas=_twocategoryDatas;
@synthesize threecategoryDatas=_threecategoryDatas;

@synthesize sortDatas=_sortDatas;
@synthesize brandDatas=_brandDatas;
@synthesize isSetUpBgScrollView=_isSetUpBgScrollView;
@synthesize currentCategory1=_currentCategory1;
@synthesize currentCategory2=_currentCategory2;
@synthesize currentCategory3=_currentCategory3;
@synthesize endmessage=_endmessage;
@synthesize timestamp=_timestamp;
//
@synthesize comboxview=_comboxview;
@synthesize lastOffsetY=_lastOffsetY;
@synthesize comboxOpen=_comboxOpen;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [UMengShare event:CK_JIANHUOCATEGORY acc:1];
    self.view.backgroundColor =[UIColor whiteColor];
    self.navTitle = _navtitle;
    self.isIndex = NO;
    _currentPage= @"0";
    _isLoadFinished =NO;
    _isRequesting =NO;
    _lastOffsetY=0.0;
    _comboxOpen = NO;
    _endmessage=@"";
    _timestamp=@"";
    //
    _isSetUpBgScrollView =NO;
    if (!_itemDatas) {
        _itemDatas =[[NSMutableArray alloc] init];
    }
    if (!_categoryDatas) {
        _categoryDatas =[[NSMutableArray alloc] init];
    }
    
    if (!_twocategoryDatas) {
        _twocategoryDatas=[[NSMutableArray alloc] init];
    }
    if (!_threecategoryDatas) {
        _threecategoryDatas=[[NSMutableArray alloc] init];
    }
    if (!_sortDatas) {
        _sortDatas =[[NSMutableArray alloc] init];
    }
    if (!_brandDatas) {
        _brandDatas =[[NSMutableArray alloc] init];
    }
    [self reloadData];
    [self initUI];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)reloadData
{
    self.isRequesting = YES;
    self.isLoadFinished = NO;
    self.currentPage= @"0";
    _endmessage=@"";
    _timestamp=@"";
    [self getCategoryItem];
}
-(void)scrollToTop
{
    if(_myCollectionView)
    {
        [_myCollectionView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
    }
}
-(void)dealloc
{
    self.comboxview =nil;
}
-(void)clickNavEvent:(id)sender
{
    UIButton *btn =(UIButton *)sender;
    switch (btn.tag) {
        case 0:
        {
            [NSObject cancelPreviousPerformRequestsWithTarget:self];
            if (self.navigationController) {
                if (self.navigationController.viewControllers.count == 1) {
                    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                } else {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
            break;
        case 1:
        {
            NiubiSearchVC *search =[[NiubiSearchVC alloc] init];
            [self.navigationController pushViewController:search animated:NO];
            search=nil;
        }
            break;
        default:
            break;
    }
}

//=================
//=================
-(void)initUI
{
    CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    layout.minimumInteritemSpacing =5;
    layout.minimumColumnSpacing = 5;
    layout.columnCount = 2;
    
    _myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, hightAuto(65), self.view.frame.size.width, self.view.frame.size.height-hightAuto(65)) collectionViewLayout:layout];
    _myCollectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    JianbianView *j = [[JianbianView alloc] initWithFrame:self.view.bounds];
    _myCollectionView.backgroundView = j;
    _myCollectionView.backgroundColor = [UIColor colorWithRed:0.967 green:0.967 blue:0.967 alpha:1];
    _myCollectionView.alwaysBounceVertical = YES;
    _myCollectionView.delegate = self;
    _myCollectionView.dataSource = self;
    j=nil;
    layout=nil;
    //添加到主页面上去
    [self.view addSubview:_myCollectionView];
    [_myCollectionView registerClass:[RacksCollectionViewCell class] forCellWithReuseIdentifier:@"RacksCollectionViewCell"];
    [_myCollectionView registerClass:[RacksCollectionHeaderView class] forSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader
                 withReuseIdentifier:@"RacksCollectionHeaderView"];
    [_myCollectionView registerClass:[RacksCollectionFooterView class] forSupplementaryViewOfKind:CHTCollectionElementKindSectionFooter
                 withReuseIdentifier:@"RacksCollectionFooterView"];
    
    __weak typeof (self) wSelf = self;
    [_myCollectionView addInfiniteScrollingWithActionHandler:^{
        if (wSelf.isRequesting) {
            return;
        }
        if (wSelf.isLoadFinished) {
            //停止菊花
            [wSelf.myCollectionView.infiniteScrollingView stopAnimating];
            [wSelf.myCollectionView setShowsInfiniteScrolling:NO];
            return;
        }
        [wSelf.myCollectionView.infiniteScrollingView startAnimating];
        if([wSelf.itemDatas count]==0)
        {
            return;
        }
        wSelf.currentPage =[NSString stringWithFormat:@"%lu",[wSelf.itemDatas count]];
        [wSelf  getCategoryItem];
    }];
    
    
}

#pragma mark -UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.itemDatas.count;
}

//构建单元格
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"RacksCollectionViewCell";
    RacksCollectionViewCell * cell = (RacksCollectionViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    if (indexPath.row>=[self.itemDatas count]) {
        return cell;
    }
    id dict = [_itemDatas objectAtIndex:indexPath.row];
    if (dict && [dict isKindOfClass:[NSDictionary class]]) {
        [cell showInfo:dict key:@"RacksCollectionViewCell" indexPath:indexPath];
    }
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row>=[self.itemDatas count]) {
        return CGSizeMake((DEVICE_WIDTH-PHOTO_TIME_PADDING*3)/2, (DEVICE_WIDTH-PHOTO_TIME_PADDING*3)/2);
    }
    id dict = [_itemDatas objectAtIndex:indexPath.row];
    if (dict && [dict isKindOfClass:[NSDictionary class]])
    {
        float height =[RacksCollectionViewCell returnCellHeight:dict];
        return CGSizeMake((DEVICE_WIDTH-PHOTO_TIME_PADDING*3)/2, height);
    }
    
    return CGSizeMake((DEVICE_WIDTH-PHOTO_TIME_PADDING*3)/2, (DEVICE_WIDTH-PHOTO_TIME_PADDING*3)/2);
}

//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row>=[self.itemDatas count]) {
        return;
    }
    id dict = [_itemDatas objectAtIndex:indexPath.row];
    if (dict && [dict isKindOfClass:[NSDictionary class]])
    {
        WebViewController *shaidanweb =[[WebViewController alloc] init];
        shaidanweb.baoliaoDictionary=dict;
        shaidanweb.titlestr = @"storageracks";
        NSString *coupon =[[NSString stringWithFormat:@"%@",[dict objectForKey:@"coupon"]] replaceNullString] ;
        shaidanweb.dikouquan = coupon;
        [self.navigationController pushViewController:shaidanweb animated:YES];
        shaidanweb=nil;
    }
    
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *reusableView = nil;
    
    if ([kind isEqualToString:CHTCollectionElementKindSectionHeader]) {
        RacksCollectionHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                                               withReuseIdentifier:@"RacksCollectionHeaderView"
                                                                                      forIndexPath:indexPath];
        __weak typeof (self) wSelf = self;
        [header setCallBack:^(UIView *v, id d, id k) {
            [wSelf cellAction:v obj:d key:k];
        }];
        [header showInfo:self.brandDatas indexPath:indexPath];
        
        return header;
        
    } else if ([kind isEqualToString:CHTCollectionElementKindSectionFooter]) {
        
        RacksCollectionFooterView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                                               withReuseIdentifier:@"RacksCollectionFooterView"
                                                                                      forIndexPath:indexPath];
        
        [footer showinfo:_endmessage];
        
        return footer;
    }
    
    return reusableView;
}
-(void)cellAction:(UIView *)v obj:(id)obj key:(id)key
{
    NSString *title = [NSString stringWithFormat:@"%@",obj];
    if([title isEqualToString:@"更多品牌..."])
    {
        StorageBrandViewController *brands = [[StorageBrandViewController alloc] init];
        brands.currentCategory1 =self.currentCategory1;
        brands.currentCategory2 =self.currentCategory2;
        brands.currentCategory3 =self.currentCategory3;
        __weak typeof (self) wSelf = self;
        [brands setCallBack:^(UIView *v, id o, id k, id i) {
            if (o && [o isKindOfClass:[NSDictionary class]]) {
                wSelf.currentBrand = [o objectForKey:@"id"];
                wSelf.isRequesting = YES;
                wSelf.isLoadFinished = NO;
                wSelf.currentPage= @"0";
                [ZShare showAnimationView:wSelf.view center:wSelf.view.center];
                [wSelf getCategoryItem];
            }
        }];
        [self.navigationController pushViewController:brands animated:YES];
        brands=nil;
        return;
    }else{
        __block NSDictionary *dict = nil;
        [self.brandDatas enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj && [obj isKindOfClass:[NSDictionary class]]) {
                NSString *name = [obj objectForKey:@"name"];
                if ([name isEqualToString:title]) {
                    dict = [NSMutableDictionary dictionaryWithDictionary:obj];
                    *stop = YES;
                    return;
                }
            }
        }];
        if (dict && [dict isKindOfClass:[NSDictionary class]]) {
            self.currentBrand = [dict objectForKey:@"id"];
            self.isRequesting = YES;
            self.isLoadFinished = NO;
            self.currentPage= @"0";
            [ZShare showAnimationView:self.view center:self.view.center];
            [self getCategoryItem];
        }
    }
}
//=================================
//
//=================================
-(void)getCategoryItem
{
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:self.currentPage forKey:@"from"];
    [dict setValue:_currentSort forKey:@"sort"];
    [dict setValue:_currentCategory1 forKey:@"cate1"];
    [dict setValue:_currentCategory2 forKey:@"cate2"];
    [dict setValue:_currentCategory3 forKey:@"cate3"];
    [dict setValue:_currentBrand forKey:@"brand"];
    if (![self.currentPage isEqualToString:@"0"] && self.timestamp.length>0) {
        [dict setValue:_timestamp forKey:@"timestamp"];
    }
    __weak typeof (self) wSelf = self;
    [StorageInfo getStoreRacksCategoryItems:dict success:^(AFHTTPRequestOperation *operation, id result) {
        wSelf.isRequesting = NO;
        [wSelf parserResultObject:result];
        [ZShare hiddenAnimationView:wSelf.view];
        [wSelf.myCollectionView.infiniteScrollingView stopAnimating];
    } failure:^(NSError *error) {
        [ZShare hiddenAnimationView:wSelf.view];
        [wSelf.myCollectionView.infiniteScrollingView stopAnimating];
    }];
    
}
-(void)parserResultObject:(id)resultObject
{
    if (resultObject==nil) {
        return;
    }
    if (resultObject && [resultObject isKindOfClass:[NSDictionary class]]) {
        id brands =[resultObject objectForKey:@"brands"];
        if (brands && [brands isKindOfClass:[NSArray class]] && [brands count]>0) {
            [self.brandDatas removeAllObjects];
            [self.brandDatas addObjectsFromArray:brands];
            CHTCollectionViewWaterfallLayout *layout = (CHTCollectionViewWaterfallLayout *)self.myCollectionView.collectionViewLayout;
            layout.headerHeight = [RacksCollectionHeaderView returnCellHeight:self.brandDatas];
        }
        
        id items =[resultObject objectForKey:@"items"];
        if (items && [items isKindOfClass:[NSArray class]] &&[items count]>0) {
            
            if ([self.currentPage intValue]==0) {
                [self.myCollectionView setShowsInfiniteScrolling:YES];
                [self.itemDatas removeAllObjects];
            }
            _endmessage=@"";
            [self.itemDatas addObjectsFromArray:items];
        }else
        {
            if ([self.currentPage intValue]==0) {
                [self.myCollectionView setShowsInfiniteScrolling:YES];
                [self.itemDatas removeAllObjects];
            }
        }
        if ([self.currentPage intValue]==0) {
            NSInteger ttimestamp = [[resultObject objectForKey:@"timestamp"] integerValue];
            if (ttimestamp>=0) {
                self.timestamp = [NSString stringWithFormat:@"%ld",ttimestamp];
            }
        }
        
        self.isLoadFinished =  [[resultObject objectForKey:@"end"] boolValue];
        if (self.isLoadFinished) {
            [self.myCollectionView.infiniteScrollingView stopAnimating];
            CHTCollectionViewWaterfallLayout *layout = (CHTCollectionViewWaterfallLayout *)self.myCollectionView.collectionViewLayout;
            layout.footerHeight =80;
            
            _endmessage =[resultObject objectForKey:@"end_msg"];
            [self.myCollectionView setShowsInfiniteScrolling:NO];
        }
    }
    //end
    [self.myCollectionView reloadData];
}
@end
